﻿//-----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation.  All rights reserved.
//-----------------------------------------------------------------------------

using System;

namespace AppToolkit.WF.Utils
{

    /// <summary>
    /// An AsyncResult that completes as soon as it is instantiated.
    /// </summary>
    public class CompletedAsyncResult : AsyncResult
    {
        /// <summary>
        /// CTOR
        /// </summary>
        /// <param name="callback"></param>
        /// <param name="state"></param>
        public CompletedAsyncResult(AsyncCallback callback, object state)
            : base(callback, state)
        {
            Complete(true);
        }

        /// <summary>
        /// Call to wait for completion of the underlying operation.
        /// </summary>
        /// <param name="result"></param>
        public static void End(IAsyncResult result)
        {
            AsyncResult.End<CompletedAsyncResult>(result);
        }
    }

    /// <summary>
    /// Typed <see cref="AsyncResult"/> implementation.
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class CompletedAsyncResult<T> : AsyncResult
    {
        readonly T _data;

        /// <summary>
        /// CTOR
        /// </summary>
        /// <param name="data"></param>
        /// <param name="callback"></param>
        /// <param name="state"></param>
        public CompletedAsyncResult(T data, AsyncCallback callback, object state)
            : base(callback, state)
        {
            this._data = data;
            Complete(true);
        }

        /// <summary>
        /// Call to wait for completion of the underlying operation.
        /// </summary>
        /// <param name="result"></param>
        /// <returns></returns>
        public static T End(IAsyncResult result)
        {
            var completedResult = AsyncResult.End<CompletedAsyncResult<T>>(result);
            return completedResult._data;
        }
    }
}
